package edu.hda.pt.server.connections.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import edu.hda.pt.server.connections.PTServerMINA;
import edu.hda.pt.utils.Stream;
import edu.hda.pt.utils.TestObject;

/**
 * Event handler for the MINA server
 * 
 * @author Marc Hammerton
 * 
 */
public class ServerProtocolHandler extends IoHandlerAdapter {

	private PTServerMINA server;

	/**
	 * Constructor setting the server object
	 * 
	 * @param server
	 *            - the server object
	 */
	public ServerProtocolHandler(PTServerMINA server) {
		this.server = server;
	}

	/**
	 * This method is called whenever an exception is caught. It closes the
	 * session and prints the exception.
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#exceptionCaught(IoSession,
	 *      Throwable)
	 */
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) {
		System.out.println(server.serverID + " exception caught, disconnect");
		cause.printStackTrace();
		session.close(true);
	}

	/**
	 * This method is called when a message from the client is received. It
	 * calls the appropriate server method and sends the response back to the
	 * client.
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(IoSession,
	 *      Object)
	 */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

		if (message instanceof Boolean) {
			boolean response = server.handleBool((Boolean) message);
			session.write(response);
		} else if (message instanceof byte[]) {
			byte[] response = server.handleBytes((byte[]) message);
			session.write(response);
		} else if (message instanceof Integer) {
			int response = server.handleInteger((Integer) message);
			session.write(response);
		} else if (message instanceof Long) {
			long response = server.handleLong((Long) message);
			session.write(response);
		} else if (message instanceof TestObject) {
			TestObject response = server.handleObject((TestObject) message);
			session.write(response);
		} else if (message instanceof String) {
			String response = server.handleString((String) message);
			session.write(response);
		} else if (message instanceof Stream) {
			Stream stream = (Stream) message;
			server.handleStream(stream, session);
		}

	}

	/**
	 * This method is called when the session is idle for a certain time span.
	 * It then closes the session.
	 * 
	 * @see org.apache.mina.core.service.IoHandlerAdapter#sessionIdle(IoSession, IdleStatus)
	 */
	@Override
	public void sessionIdle(IoSession session, IdleStatus status) {
		session.close(true);
	}

}
